import time
from mediadart.mqueue.mqclient_twisted import Proxy
from twisted.internet import reactor

XMAX=11
YMAX=11

def print_result(result, a, b):
    print '%d * %d = %s' % (a, b, result)
    return result

def print_error(failure):
    print 'ERROR@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ %s' % failure

def print_time_exit(_, t0):
    t1 = time.time()
    print 'elapsed = %.3f' % (t1-t0)
    #reactor.stop()

def run(xmax, ymax):
    t0 = time.time()
    print 'start: %.3f' % t0
    #p = Proxy('Calculator', reply_url='http://localhost:8080/reply2/abc22')
    p = Proxy('Calculator')
    for i in xrange(xmax):
        for j in xrange(ymax):
            d = p.prod(i, j)
            d.addCallback(print_result, i, j)
            d.addErrback(print_error)
    print 'adding final callback to %d' % id(d)
    d.addCallbacks(print_time_exit, print_error, callbackArgs=[t0])
    #t1 = time.time()
    #print 'elapsed = %.3f' % (t1-t0)
#    reactor.stop()

def start():
    reactor.callLater(1, run, XMAX, YMAX)

reactor.callWhenRunning(run, XMAX, YMAX)
reactor.run()
